/*
 * This work is licensed under a GNU General Public License 
 * (http://www.gnu.org/copyleft/gpl.html).
 * 
 * Title: 		Mobup
 * Version: 		0.3
 * Description:         Mobile uploader for Flickr
 * Creator:             Vincenzo Lembo and Matteo Penzo
 * Source:              http://mobup.org
 *
 */

package ctmobup.utils;

import java.io.*;
import javax.microedition.io.*;


/*
 * HTTP Class
 * 
 * This class allows to send GET and POST request to a web server
 *
 */

public class HTTP {
    
    /** Creates a new instance of HTTP */
    public HTTP() {
        
    }


    /*
     * send a POST request to Web server
     */
    public static String sendPostRequest(String requeststring,String url,String boundary) {
            HttpConnection hc = null;
            DataInputStream dis = null;
            DataOutputStream dos = null;
            StringBuffer messagebuffer = new StringBuffer();
            try 
            {
                // Open up an http connection with the Web server
                // for both send and receive operations
                hc = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
                // Set the request method to POST
                hc.setRequestMethod(HttpConnection.POST);
                //add property for the multipart/form-data Content-Type
                hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                
                // Send the string entered by user byte by byte
                dos = hc.openDataOutputStream();
                byte[] request_body = requeststring.getBytes();
                for (int i = 0; i < request_body.length; i++) {
                        dos.writeByte(request_body[i]);
                }
                
                dos.close();

                // Retrieve the response back from the servlet
                messagebuffer.append(hc.getResponseMessage() + "\r\n");
                dis = new DataInputStream(hc.openInputStream());
                int ch;
                // Check the Content-Length first
                long len = hc.getLength(); 
                if(len!=-1) 
                {
                        for(int i = 0;i<len;i++)
                        {
                                if((ch = dis.read())!= -1)
                                {
                                        messagebuffer.append((char)ch);
                                }
                        }
                } 
                else 
                {
                    // if the content-length is not available
                    while ((ch = dis.read()) != -1)
                            messagebuffer.append((char) ch);
                    
                }
                dis.close();
 
            } catch (IOException ioe) {
                    messagebuffer = new StringBuffer("ERROR!");
                    
            } finally {
                    // Free up i/o streams and http connection
                    try { 
                            if (hc != null) hc.close();
                    } catch (IOException ignored) {}
                    try { 
                            if (dis != null) dis.close();
                    } catch (IOException ignored) {}
                    try { 
                            if (dos != null) dos.close();
                    } catch (IOException ignored) {}
            }
            return messagebuffer.toString();
    }
    
    public static String sendPostRequest(String before, byte[] photoData, String after, String url,String boundary) {
        HttpConnection hc = null;
        DataInputStream dis = null;
        DataOutputStream dos = null;
        StringBuffer messagebuffer = new StringBuffer();
        try 
        {
            // Open up an http connection with the Web server
            // for both send and receive operations
            hc = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
            // Set the request method to POST
            hc.setRequestMethod(HttpConnection.POST);
            //add property for the multipart/form-data Content-Type
            hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            
            // Send the string entered by user byte by byte
            dos = hc.openDataOutputStream();
            byte[] beforeBytes = before.getBytes();
            for (int i = 0; i < beforeBytes.length; i++) {
                    dos.writeByte(beforeBytes[i]);
            }
            for (int i = 0; i < photoData.length; i++) {
                dos.writeByte(photoData[i]);
            }
            byte[] afterBytes = after.getBytes();
            for (int i = 0; i < afterBytes.length; i++) {
                    dos.writeByte(afterBytes[i]);
            }
            dos.close();

            // Retrieve the response back from the servlet
            messagebuffer.append(hc.getResponseMessage() + "\r\n");
            dis = new DataInputStream(hc.openInputStream());
            int ch;
            // Check the Content-Length first
            long len = hc.getLength(); 
            if(len!=-1) 
            {
                    for(int i = 0;i<len;i++)
                    {
                            if((ch = dis.read())!= -1)
                            {
                                    messagebuffer.append((char)ch);
                            }
                    }
            } 
            else 
            {
                // if the content-length is not available
                while ((ch = dis.read()) != -1)
                        messagebuffer.append((char) ch);
                
            }
            dis.close();

        } catch (IOException ioe) {
                messagebuffer = new StringBuffer("ERROR!");
                
        } finally {
                // Free up i/o streams and http connection
                try { 
                        if (hc != null) hc.close();
                } catch (IOException ignored) {}
                try { 
                        if (dis != null) dis.close();
                } catch (IOException ignored) {}
                try { 
                        if (dos != null) dos.close();
                } catch (IOException ignored) {}
        }
        return messagebuffer.toString();
    }
    
    /*
     * send a GET request to Web server
     */
    public static String sendGetRequest(String url) {
            HttpConnection hc = null;
            DataInputStream dis = null;
            DataOutputStream dos = null;
            StringBuffer messagebuffer = new StringBuffer();
            try 
            {
                // Open up an http connection with the Web server
                // for both send and receive operations
                hc = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
                // Set the request method to POST
                hc.setRequestMethod(HttpConnection.GET);
                
  
                // Retrieve the response back from the servlet
                messagebuffer.append(hc.getResponseMessage() + "\r\n");
                dis = new DataInputStream(hc.openInputStream());
                int ch;
                // Check the Content-Length first
                long len = hc.getLength(); 
                if(len!=-1) 
                {
                        for(int i = 0;i<len;i++)
                        {
                                if((ch = dis.read())!= -1)
                                {
                                        messagebuffer.append((char)ch);
                                }
                        }
                } 
                else 
                {
                        // if the content-length is not available
                        while ((ch = dis.read()) != -1)
                                messagebuffer.append((char) ch);
                }
                dis.close();
 
            } catch (IOException ioe) {
                    messagebuffer = new StringBuffer("ERROR!");
                    
            } finally {
                    // Free up i/o streams and http connection
                    try { 
                            if (hc != null) hc.close();
                    } catch (IOException ignored) {}
                    try { 
                            if (dis != null) dis.close();
                    } catch (IOException ignored) {}
                    try { 
                            if (dos != null) dos.close();
                    } catch (IOException ignored) {}
            }
            return messagebuffer.toString();
    }
}
